package com.dongdongshop.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongdongshop.constant.HttpResultEnum;
import com.dongdongshop.constant.RedisAdvertConst;
import com.dongdongshop.data.DataResult;
import com.dongdongshop.pojo.content.TbContent;
import com.dongdongshop.service.content.ContentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * 首页广告
 * @Author Eayon
 * @Date 2020/3/3 14:21
 */
@Controller
@RequestMapping("content")
public class ContentController {

    private static final Logger log = LoggerFactory.getLogger(ContentController.class);

    @Autowired
    private RedisTemplate redisTemplate;

    @Reference(check = false)
    private ContentService contentService;

    /**
     * 获取首页类型广告信息
     * @param categoryId
     * @return
     */
    @RequestMapping(value = "getContentByCategoryId",method = RequestMethod.POST)
    @ResponseBody
    public DataResult getContentByCategoryId(Long categoryId){
        List<TbContent> contents = null;
        try {
            //判断如果redis中没有该类型广告数据
            if(!redisTemplate.boundHashOps(RedisAdvertConst.INDEXADVER).hasKey(RedisAdvertConst.CATEGORY+categoryId)){
                //从数据库中查询并存入缓存
                contents = contentService.findContentByCategoryId(categoryId);
                redisTemplate.boundHashOps(RedisAdvertConst.INDEXADVER).put(RedisAdvertConst.CATEGORY+categoryId,contents);
            }else{
                contents = (List<TbContent>)redisTemplate.boundHashOps(RedisAdvertConst.INDEXADVER).get(RedisAdvertConst.CATEGORY + categoryId);
            }
        }catch (Exception e){
            log.error("初始化首页广告异常",e);
            return new DataResult(HttpResultEnum.ERROR.getCode(),HttpResultEnum.ERROR.getMessage());
        }
        return new DataResult(HttpResultEnum.SUCCESS.getCode(),HttpResultEnum.SUCCESS.getMessage(),contents);
    }
}
